package com.dz.gateway.util;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import java.util.Date;

/**
 * 描述
 *
 * @author www.itheima.com
 * @version 1.0
 * @package entity *
 * @since 1.0
 */
public class JwtUtil {
    //有效期为
    public static final Long JWT_TTL = 1800000L;// 30 * 60 *1000  半小时

    //Jwt令牌信息
    public static final String JWT_SECRET = "bud_uncle";

    /**
     * 生成令牌
     * @param id
     * @param subject
     * @param ttlMillis
     * @return
     */
    public static String createJWT(String id, String subject, Long ttlMillis) {

        //当前系统时间
        long nowMillis = System.currentTimeMillis();
        //令牌签发时间
        Date now = new Date(nowMillis);

        //如果令牌有效期为null，则默认设置有效期半小时
        if (ttlMillis == null) {
            ttlMillis = JwtUtil.JWT_TTL;
        }

        //令牌过期时间设置
        long expMillis = nowMillis + ttlMillis;
        Date expDate = new Date(expMillis);

        Algorithm algorithm = Algorithm.HMAC256(JWT_SECRET);
        //封装Jwt令牌信息
        return JWT.create()
                .withJWTId(id)
                .withSubject(subject)
                .withIssuer("dzm")
                .withIssuedAt(now)
                .withExpiresAt(expDate)
                .sign(algorithm);
    }

    /**
     * 生成加密 secretKey
     *
     * @return
     */



    /**
     * 解析令牌数据
     *
     * @param jwt
     * @return
     * @throws Exception
     */
    public static String parseJWT(String token) throws Exception {
        Algorithm algorithm = Algorithm.HMAC256(JWT_SECRET);
        JWTVerifier verifier = JWT.require(algorithm).build();
        DecodedJWT jwt = verifier.verify(token);
        String subject = jwt.getSubject();
        return subject;
    }

    public static void main(String[] args) {
        String jwt = JwtUtil.createJWT("weiyibiaoshi", "aaaaaa", null);
        System.out.println(jwt);
        try {
            String s = JwtUtil.parseJWT(jwt);
            System.out.println(s);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
